import { onMounted, onBeforeMount, onBeforeUnmount } from 'vue'
import { useDebounceFn } from '@vueuse/core'
import { useAppConfigStore } from '@/stores'
import { addEventListen, removeEventListen } from '@/utils/event'

export type BreakPoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl'

const breakPoint = ref<BreakPoint>('xl')
// 监听屏幕变化
const resize = (e: UIEvent) => {
  const width = (e.target as Window).innerWidth
  switch (!!width) {
    case width < 768:
      breakPoint.value = 'xs'
      break
    case width >= 768 && width < 992:
      breakPoint.value = 'sm'
      break
    case width >= 992 && width < 1200:
      breakPoint.value = 'md'
      break
    case width >= 1200 && width < 1920:
      breakPoint.value = 'lg'
      break
    case width >= 1920:
      breakPoint.value = 'xl'
      break
  }
}

const MobileWidth = 992 // https://arco.design/vue/component/grid#responsivevalue
const PhoneWidth = 767

function queryDevice() {
  const rect = document.body.getBoundingClientRect()
  const isMobile = rect.width - 1 < MobileWidth
  const isPhone = rect.width - 1 < PhoneWidth
  return [isMobile, isPhone]
}

export default function useResponsive(immediate?: boolean) {
  const appConfigStore = useAppConfigStore()
  function resizeHandler() {
    if (!document.hidden) {
      const [isMobile, isPhone] = queryDevice()
      appConfigStore.toggleIsMobile(isMobile)
      appConfigStore.toggleIsPhone(isPhone)
    }
  }
  const debounceFn = useDebounceFn(resizeHandler, 500)
  onMounted(() => {
    if (immediate) debounceFn()
  })
  onBeforeMount(() => {
    addEventListen(window, 'resize', debounceFn)
  })
  onBeforeUnmount(() => {
    removeEventListen(window, 'resize', debounceFn)
  })
}
